{% extends "stream/base.html" %}

{% block title %}
Your entries
{% endblock %}

{% block scripts %}
    <script type="text/javascript" src="/js/common.js"></script>
    <script type="text/javascript" src="/js/jquery.mousewheel.js"></script>
    <script type="text/javascript">
        var page_data = {
            current_entry: null,
            more_entries: true, // There are more entries for this thread on the server
            pending_entries: false, // Request for entries has not returned yet
            entries: null,
            subscriptions: null,
            tags: null
        };

        var display_settings = null;

        function AbsoluteTop(element) {
            var top = 0;
            do {
                top += element.offsetTop;
            } while (element = element.offsetParent);
            return top;
        }

        const EntriesPerRequest = 20; // How many entries to request
        const MaxRemainingEntries = 5; // How many entries must remain in a stream to ask for more

        function RequestDisplaySettings() {
            $.getJSON('{% url stream.views.displaySettings %}', {}, function(data) {
                display_settings = data;
                ApplyDisplaySettings();
            })
        }

        function ApplyDisplaySettings() {
            GenerateHideButton($('.SubscriptionList'), 'display_subscriptions', display_settings.display_subscriptions != 'show');
            GenerateHideButton($('.TagList'), 'display_tags', display_settings.display_tags != 'show');
        }

        function RequestEntries(owner_id, tags, subscription) {
            var parameters = new Parameters();
            if (owner_id != undefined) {
                parameters.owner_id = owner_id;
            }
            if (tags != undefined) {
                parameters.tags = TagsToPath(tags);
            }
            if (subscription != undefined) {
                parameters.subscription = subscription;
            }
            parameters.first = null != page_data.entries ? page_data.entries.length : 0;
            parameters.count = EntriesPerRequest;
            if (page_stats.unread_only) {
                parameters.unread_only = true;
            }
            if (page_stats.favorite_only) {
                parameters.favorite_only = true;
            }
            // Need to suppress percent-encoding of tag string
            $.ajaxSetup({
                processData: false
            })
            page_data.pending_entries = true;
            $.getJSON('/getEntries', parameters.toString(), function(data) {
                page_data.pending_entries = false;
                if (page_data.entries == null) {
                    page_data.entries = data;
                } else {
                    page_data.entries = page_data.entries.concat(data);
                }
                if (data.length < EntriesPerRequest) {
                    page_data.more_entries = false;
                }
                $.each(data, function(i, item) {
                    $('.Stream').append(GenerateEntryMarkup(item))
                })
            })
            $.ajaxSetup({
                processData: true
            })
        }

        function RequestTags(owner_id) {
            parameters = new Parameters();
            if (owner_id != undefined) {
                parameters.owner_id = owner_id;
            }
            $.getJSON('/getTags', parameters.toString(), function(data) {
                page_data.tags = data;
                $.each(data, function(i, item) {
                    if (item.name.length > 15) {
                        display_name = item.name.substr(0, 15) + '...';
                    } else {
                        display_name = item.name;
                    }
                    $('.TagList').append(
                        $('<li/>').addClass('Tag').append(
                            GenerateLinkMarkup('span', TagLink(item.name), display_name, ['TagName'], null)
                        ).append(
                            $('<span/>').addClass('TagCount').text(item.count)
                        )
                    )
                })
            })
        }

        function RequestSubscriptions() {
            $.getJSON('/getSubscriptions', '', function(data) {
                page_data.subscriptions = data;
                $.each(data, function(i, item) {
                    delete_parameters = [{ name : 'Yes, but keep messages', params : { 'type' : 'subscription'}},
                        { name : 'Yes, and messages that are only in it', params : { 'type' : 'this_messages' }},
                        { name : 'Yes, and all messages in it', params : { 'type' : 'all_messages' }}]
                    var item_name = item.unread > 0 ? item.name + ' (' + item.unread + ')' : item.name;
                    $('.SubscriptionList').append(
                        $('<li id="subscription-' + item.id + '"/>').append(
                            GenerateLinkMarkup('div', SubscriptionLink(item.id), item_name, ['Subscription'], null)
                        ).append(
                            $('<div class="SubscriptionActions"/>').append(
                                $('<span class="Action">Edit</span>').bind('click', function(e) {
                                    document.location.href = SubscriptionEditLink(item.id);
                                })
                            ).append(
                                createDeleteAction('subscription', item.id, delete_parameters)
                            )
                        )
                    )
                })
            })
        }

        function GenerateHideButton(controlled, id, is_hidden) {
            var div = $('<div id="' + id + '" class="HideButton"/>');
            var setup_button = function() {
                var hide = div.attr('hidden') == 'false';
                if (hide) {
                    controlled.addClass('Hidden');
                } else {
                    controlled.removeClass('Hidden');
                }
                div.attr('hidden', hide);
                div.text(hide ? 'Show' : 'Hide');
                display_settings[div.attr('id')] = hide ? 'hide' : 'show';
            }
            // Set the opposite and then simulate a click
            div.attr('hidden', !is_hidden);
            div.bind('click', function() {
                setup_button();
                $.post('{% url stream.views.displaySettings %}', display_settings);
            });
            controlled.parent().append(div);
            setup_button();
        }

        function GenerateEntryMarkup(item) {
            var entry = item.entry;
            if (!entry.hasOwnProperty('title')) {
                entry.title = entry.link;
            }
            var entry_div = $('<li/>').addClass('Entry').append(
                $('<div/>').append(
                    GenerateLinkMarkup('span', entry.link, entry.title, ['EntryTitle'], null)
                ).append(
                    $('<span class="EntryCreated">' + entry.created + '</div>')
                )
            ).append(
                $('<div/>').addClass('EntryContent').append(
                    entry.hasOwnProperty('description') ? entry.description : ''
                )
            ).attr('id', 'message-' + item.id);
            var entry_footer = $('<div class="EntryFooter"/>');
            for (var i = 0; i < item.tags.length; ++i) {
                var tag = item.tags[i];
                entry_footer.append(
                    $('<div/>').addClass('EntryTag').append(
                        $('<a/>').attr('href', TagLink(tag.name)).text(tag.name)
                    )
                )
            }
            if (page_stats.is_owner) {
                entry_footer.append(
                    $('<div class="EntryActions"/>').append(
                        $('<span class="Action"/>').append(
                            item.published ? 'Unpublish' : 'Publish'
                        ).bind('click', function(e) {
                            $.post('/edit', { id: item.id, published: !item.published }, function(data) {
                                var markup = GenerateEntryMarkup(data);
                                $('#message-' + item.id).replaceWith(markup)
                            }, 'json');
                            return false;
                        })
                    ).append(
                        $('<span class="Action">Edit</span>').bind('click', function(e) {
                            ShowEditEntry($('#message-' + item.id));
                        })
                    ).append(
                        createDeleteAction('message', item.id)
                    )
                )
            }
            entry_div.append(entry_footer);
            return entry_div;
        }

        function ShowEditEntry(entry_div) {
            entry = Filter(page_data.entries, function(data) {
                return data.id == entry_div.attr('id').split('-')[1];
            });
            if (entry.length > 0) {
                entry = entry[0];
            } else {
                return;
            }
            var form_id = 'edit-message-' + entry.id;
            function ResetEntryMarkup() {
                $('#' + form_id).replaceWith(GenerateEntryMarkup(entry))
            }
            edit_form = $('<form class="Container" id="' + form_id + '" action="{% url stream.views.editMessage %}" method="POST" />').append(
                //'<div class="Field">Title: <input type="text" name="title" value="' + entry.entry.title + '"/></div>'
            //).append(
                '<div class="Field">Tags: <input type="text" name="tags" value="' + Map(entry.tags, function(e) { return e.name; }).join(' ') + '"/></div>'
            ).append(
                '<input type="hidden" name="id" value="' + entry.id + '"/>'
            )
            var footer = $('<div class="EntryFooter"/>');
            footer.append(
                $('<div class="EntryActions"/>').append(
                    $('<span class="Action">Save</span>').bind('click', function(e) {
                        var form = $('#' + form_id)
                        $.post(form.attr('action'), form.serialize(), function(data) {
                            var markup = GenerateEntryMarkup(data);
                            $('#' + form_id).replaceWith(markup)
                        }, 'json');
                    })
                ).append(
                    $('<span class="Action">Cancel</span>').bind('click', function(e) {
                        ResetEntryMarkup()
                    })
                )
            );

            edit_form.append(footer);
            $(entry_div).replaceWith(edit_form);
        }

        function ResizeStream() {
            stream = $('.Stream');
            // Set up content space height
            var height = window.innerHeight - AbsoluteTop(stream.get(0));
            stream.css('height', height);
        }

        function HandleStreamScroll() {
            // Find the last entry whose top is hidden over the top edge of the Stream - it is current entry.
            var stream = $('.Stream');
            var scroll_height = stream.scrollTop();
            stream = stream.children();
            total_height = 0;
            var current = null;
            for (var i = 0; i < stream.length; ++i) {
                var new_total_height = total_height + stream[i].offsetHeight;
                if (total_height < scroll_height && new_total_height > scroll_height) {
                    current = i;
                    break;
                }
                total_height = new_total_height;
            }
            if (current != null && page_data.current_entry != current) {
                var parameters = new Parameters();
                parameters.id = page_data.entries[current].id;
                parameters.read = true;
                $.post('{% url stream.views.editMessage %}', parameters.toString());
            }
            page_data.current_entry = current;
            if (page_data.entries.length  - page_data.current_entry <= MaxRemainingEntries && page_data.more_entries && !page_data.pending_entries) {
                RequestEntries(page_stats.user, page_stats.tags, page_stats.subscription);
            }
        }

        function Init() {
            if (!page_stats.is_owner) {
                $('.Stream').prepend(
                    GenerateLinkMarkup('div', null, 'Subscribe to this stream', null, function(e) {
                        $.ajaxSetup({
                            processData: false
                        })
                        var parameters = new Parameters();
                        parameters['id'] = page_stats.user;
                        parameters['tags'] = TagsToPath(page_stats.tags);
                        $.post('/subscribe', parameters.toString(), function(response) {
                            alert(response);
                        }, 'text');
                        $.ajaxSetup({
                            processData: true
                        })
                        return false;
                    })
                );
            }

            $('#add').bind('click', function(e) {
                location.href = '{% url stream.views.add %}';
            });

            RequestEntries(page_stats.user, page_stats.tags, page_stats.subscription);
            RequestTags(page_stats.user);
            if (page_stats.is_owner) {
                $('.SideBar').append('<div id="SubscriptionContainer" class="Container">\n<h3>Subscriptions</h3><ul class="SubscriptionList"></ul></div>');
                RequestSubscriptions();
            }

            RequestDisplaySettings();

            $('#TagInput').attr('value', tags.join(' '));
            $('#TagForm').submit(function() {
                var tags = $('#TagInput').attr('value').split(/\s+/);
                NavigateToStats(page_stats.user, tags, page_stats.subscription, page_stats.unread);
                return false;
            })

            if (page_stats.tags.length > 0) {
                $('.RecommendationLinks').append(
                    GenerateLinkMarkup('div', '/searchUsers/tag/' + TagsToPath(page_stats.tags), 'Users who have similar tags')
                )
            }

            {% if viewer.is_authenticated %}
            if (page_stats.tags.length > 0 || page_stats.subscription != null || !page_stats.is_owner) {
                $('.UserSpace').before(
                    GenerateLinkMarkup('div', '{% url stream.views.stream viewer.id %}', 'Back to your main stream')
                )
            }
            {% endif %}


            if (page_stats.is_owner) {
                var all_entries = GenerateLinkMarkup('span', GetPathToStats(page_stats.user, page_stats.tags, page_stats.subscription, false, page_stats.favorite_only), 'All entries', ['Action'], null, 'ReadAndUnread');
                var unread_entries = GenerateLinkMarkup('span', GetPathToStats(page_stats.user, page_stats.tags, page_stats.subscription, true, page_stats.favorite_only), 'Unread entries', ['Action'], null, 'UnreadOnly');
                if (page_stats.unread_only) {
                    unread_entries.addClass('Active');
                } else {
                    all_entries.addClass('Active');
                }
                $('.UserSpace').before(
                    $('<div/>').append(all_entries).append(unread_entries)
                )

                var all_entries = GenerateLinkMarkup('span', GetPathToStats(page_stats.user, page_stats.tags, page_stats.subscription, page_stats.unread_only, false), 'All entries', ['Action'], null, 'AllEntries');
                var favorite_entries = GenerateLinkMarkup('span', GetPathToStats(page_stats.user, page_stats.tags, page_stats.subscription, page_stats.unread_only, true), 'Entries from favorite blogs', ['Action'], null, 'FavoriteOnly');
                if (page_stats.favorite_only) {
                    favorite_entries.addClass('Active');
                } else {
                    all_entries.addClass('Active');
                }
                $('.UserSpace').before(
                    $('<div/>').append(all_entries).append(favorite_entries)
                )
            }

            ResizeStream();
            window.onresize = ResizeStream;

            var stream = $('.Stream');
            stream.bind('scroll', HandleStreamScroll);

            bookmark_js = "javascript:(function(){url='" + location.protocol + "//" + location.host + "{% url stream.views.add%}" + "?type=bookmark_form&link=' + encodeURIComponent(window.location.href) + '&save=close';window.open(url, 'bookmark');})()"
            $('#add').after(
                $('<div id="Tools">Bookmarking: drag this <a href="' + bookmark_js + '">Bookmark on Streaminatr</a> link to your Bookmarks Toolbar</div>')
            )
        }

        $(document).ready(Init);

    </script>
{% endblock %}

{% block content %}
<button id="add" type="button">Add new content</button>

<!-- Display the tag selection -->
<form id="TagForm" method="POST" action="/processTags">
    Display tags: <input id="TagInput" type="text"/>
    <input type="submit" value="Show"/>
</form>

<div class="RecommendationLinks">
    <div>
        <a href="/searchUsers">Users you may be interested in</a>
    </div>
</div>

<div class="UserSpace">
    <ul id="stream" class="Stream">
    </ul>
</div>
<div class="SideBar">
    <div id="TagContainer" class="Container">
        <h3>Tags</h3>
        <ul class="TagList"></ul>
    </div>
</div>

{% endblock %}
